<?php
namespace app\admin\model;
use think\Request;
use think\Db;
use think\Model;
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class Index extends Model
{
    //外网ip
    function get_outer()
    {
        //$year=date('Y',time());
       // $url = 'http://'.$year.'.ip138.com/ic.asp';
        $url = 'http://20019.ip138.com/ic.asp';
        $info = file_get_contents($url);
        preg_match('|<center>(.*?)</center>|i', $info, $m);
        $new_ip = explode('[', $m[1]);
        $new_ip = explode(']', $new_ip[1]);
        return $new_ip[0];
    }
    //压缩图片
    public function ys_img($source,$dst_img,$type,$percent=0.5,$size){
        $file = $source;
        //$percent = 0.3;  //图片压缩比
        if($size>0 && $size<=102400){//100k以下
            return;
            //$percent=0.9;//图片压缩比
        }elseif($size>102400 && $size<=204800){//200k以下
            $percent=0.8;//图片压缩比
        }elseif($size>204800 && $size<=307200){//300k以下
            $percent=0.7;//图片压缩比
        }elseif($size>307200 && $size<=409600){//400k以下
            $percent=0.6;//图片压缩比
        }elseif($size>409600 && $size<=512000){//500k以下
            $percent=0.5;//图片压缩比
        }elseif($size>512000 && $size<=614400){//600k以下
            $percent=0.4;//图片压缩比
        }elseif($size>614400){
            $percent=0.3;//图片压缩比
        }else{
            $percent=0.5;//图片压缩比
        }

        list($width, $height) = getimagesize($file); //获取原图尺寸
//缩放尺寸
        $newwidth = $width * $percent;
        $newheight = $height * $percent;
        $ename=getimagesize($file);
        $ename=explode('/',$ename['mime']);
        $ext=$ename[1];
        switch($ext){
            case "png":

                $src_im=imagecreatefrompng($file);
                break;
            case "jpeg":

                $src_im=imagecreatefromjpeg($file);
                break;
            case "jpg":

                $src_im=imagecreatefromjpeg($file);
                break;
            case "gif":

                $src_im=imagecreatefromgif($file);
                break;
        }
        $dst_im = imagecreatetruecolor($newwidth, $newheight);
        imagecopyresized($dst_im, $src_im, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
        switch($ext){
            case "png":

                imagepng($dst_im, $dst_img); //输出压缩后的图片
                break;
            case "jpeg":

                imagejpeg($dst_im, $dst_img); //输出压缩后的图片
                break;
            case "jpg":

                imagejpeg($dst_im, $dst_img); //输出压缩后的图片
                break;
            case "gif":

                imagejpeg($dst_im, $dst_img); //输出压缩后的图片
                break;
        }
        imagedestroy($dst_im);
    }
    //二维数组倒序
    function my_sort($arrays,$sort_key,$sort_order=SORT_ASC,$sort_type=SORT_NUMERIC ){
        if(is_array($arrays)){
            foreach ($arrays as $array){
                if(is_array($array)){
                    $key_arrays[] = $array[$sort_key];
                }else{
                    return false;
                }
            }
        }else{
            return false;
        }
        array_multisort($key_arrays,$sort_order,$sort_type,$arrays);
        return $arrays;
    }
    public function check_menu(){
        $request = Request::instance();
        //$url_arr=$request->dispatch()['module'];
        $url_arr=explode('/',$request->pathinfo());
        $url_arr=array_filter($url_arr);
        if(input('post.url')){
            $url=input('post.url');
        }else{
            $url=$url_arr[1].'/'.$url_arr[2];
        }
        $status=2;
        if(session('qm_uid')){
            if($url && ($url=='user/login' || $url=='index/logout')){
                $status=1;
            }else{
                if($url && session('qm_uid')>0){
                    $admin_re=Db::name('admin')->field('type')->where('id='.session('qm_uid'))->find();
                    if($admin_re) {
                        $group_re = Db::name('admin_group')->field('menu_str')->where('id=' . $admin_re['type'])->find();
                        $menu_arr=explode(',',$group_re['menu_str']);
                        $status=2;
                        foreach ($menu_arr as $k=>$v){
                            $menu_res=Db::name('menu')->field('title')->where(array('url'=>$url))->find();
                            if($menu_res){
                                $menu_re=Db::name('menu')->field('title')->where(array('id'=>$menu_arr[$k],'url'=>$url))->find();
                                if($menu_re){
                                    $status=1;continue;
                                }
                            }else{
                                $status=1;
                            }
                        }
                    }
                    if($admin_re['type']==1){
                        $status=1;
                    }
                }
            }
        }elseif($url=='index/login' || $url=='user/login'){
            $status=1;
        }

        return $status;
    }
    //发送邮件
    public function send_email($email='',$uid=''){
        //$index=new \app\admin\model\Index();
        $code=rand(100000,999999);
        session($uid.'_code',$code,20*60);
        $content='
    
        <div>亲爱的会员您好，</div>
        <br>
        <div>您正在使用 lutube 撸撸视频重置密码的服务</div>
        <div style="color: #F00">您的验证码为： '.$code.'</div>
        <br>
        <div>本验证码仅供一次使用，二十分钟后失效</div>
        <div>如有其他相关问题，请与 lutube 撸撸视频团队联系，谢谢</div>
        <br><br><br><br><br>
        <div>撸撸视频团队</div>
        <a href="mailto:lutube.cc@gmail.com" rel="noopener" target="_blank">lutube.cc@gmail.com</a>';
        $re=$this->sendEmail($email,'【全民视频】忘记密码验证信',$content);
        return $re;
    }
    /**
     * 发送邮件
     * @param  string $to        接收人邮件地址
     * @param  string $title     邮件标题
     * @param  string $contents  邮件内容 支持HTML格式
     * @param  string $type      判断是否要加附件
     * @param  string $accessory 附件的名字
     * @return                   成功返回true,失败返回错误信息
     */
    function sendEmail($to,$title,$contents,$type = '',$accessory =''){
        $mail = new PhpMailer();
        $mail->IsSMTP();
        $mail->CharSet ="UTF-8";//编码
        $mail->Debugoutput = 'html';// 支持HTML格式
        $mail->Host = 'smtp.163.com';//HOST 地址
        //$mail->Port = 25;//端口
        $mail->Port = 465;  //邮件发送端口
        $mail->SMTPAuth = true;  //启用SMTP认证
        $mail->SMTPSecure = "ssl";   // 设置安全验证方式为ssl
        $mail->SMTPAuth = true;
        $mail->Username = '15055270670@163.com';//用户名
        $mail->Password = 'hehezhuzhu9541';//密码
        $mail->SetFrom('15055270670@163.com','解说帝');//发件人地址, 发件人名称
        $mail->AddAddress($to);//收信人地址
        //$mail->Subject = "=?utf-8?B?" . base64_encode() . "?=";
        if (!empty($type)) {
            $mail->AddAttachment($type,$accessory); // 添加附件,并指定名称
        }
        $mail->Subject = $title;//邮件标题
        $mail->MsgHTML($contents);
        if ($mail->Send()){
            return true;
        }else{
            return $mail->errorMessage();
        }
    }
    public function del_file($objectKey){
        @unlink($objectKey);
    }
    function getFirstCharter($str)
    {
        if (empty($str)) {
            return '';
        }
        $str = preg_replace('/\d*/', '', $str);
        if($str){
            $fchar = ord($str{0});
            if ($fchar >= ord('A') && $fchar <= ord('z')) return strtoupper($str{0});
            $s1 = @iconv('UTF-8', 'gbk', $str);
            $s2 = @iconv('gbk', 'UTF-8', $s1);
            $s = $s2 == $str ? $s1 : $str;
            $asc = ord($s{0}) * 256 + ord($s{1}) - 65536;
            if ($asc >= -20319 && $asc <= -20284) return 'A';
            if ($asc >= -20283 && $asc <= -19776) return 'B';
            if ($asc >= -19775 && $asc <= -19219) return 'C';
            if ($asc >= -19218 && $asc <= -18711) return 'D';
            if ($asc >= -18710 && $asc <= -18527) return 'E';
            if ($asc >= -18526 && $asc <= -18240) return 'F';
            if ($asc >= -18239 && $asc <= -17923) return 'G';
            if ($asc >= -17922 && $asc <= -17418) return 'H';
            if ($asc >= -17417 && $asc <= -16475) return 'J';
            if ($asc >= -16474 && $asc <= -16213) return 'K';
            if ($asc >= -16212 && $asc <= -15641) return 'L';
            if ($asc >= -15640 && $asc <= -15166) return 'M';
            if ($asc >= -15165 && $asc <= -14923) return 'N';
            if ($asc >= -14922 && $asc <= -14915) return 'O';
            if ($asc >= -14914 && $asc <= -14631) return 'P';
            if ($asc >= -14630 && $asc <= -14150) return 'Q';
            if ($asc >= -14149 && $asc <= -14091) return 'R';
            if ($asc >= -14090 && $asc <= -13319) return 'S';
            if ($asc >= -13318 && $asc <= -12839) return 'T';
            if ($asc >= -12838 && $asc <= -12557) return 'W';
            if ($asc >= -12556 && $asc <= -11848) return 'X';
            if ($asc >= -11847 && $asc <= -11056) return 'Y';
            if ($asc >= -11055 && $asc <= -10247) return 'Z';
        }else{
            return '';
        }
    }
    public function phone_yzm($phone,$type,$code){
        //  注册验证码模板：SMS_163460670
        //  登录确认验证码: SMS_163460672
        //  修改密码验证码: SMS_163460669

        if($type==1){
            $TemplateCode='SMS_163460670';
        }elseif($type==2){
            $TemplateCode='SMS_163460672';
        }elseif($type==3){
            $TemplateCode='SMS_163460669';
        }
        AlibabaCloud::accessKeyClient('LTAIw9l7VT86UEPF', 'yhg95sKyq6BZRg84UWUYiy1VbeWQRB')
            ->regionId('cn-hangzhou') // replace regionId as you need
            ->asGlobalClient();

        try {
            $result = AlibabaCloud::rpcRequest()
                ->product('Dysmsapi')// 指定产品
                // ->scheme('https') // https | http
                ->version('2017-05-25')// 指定产品版本
                ->action('SendSms')// 指定产品接口
                ->method('POST')// 指定请求方式
                ->options([
                    'query' => [
                        'TemplateCode' => $TemplateCode,
                        'SignName' => '解说帝',
                        'PhoneNumbers' => $phone,
                        'TemplateParam' => '{"code":"'.$code.'"}',
                    ],
                ])
                ->request();
            if($result->toArray()['Code']=='OK'){
                return 1;
            }else{
                return 2;
            }
        } catch (ClientException $e) {
            return $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            return $e->getErrorMessage() . PHP_EOL;
        }
    }
    //redis  礼物列表
    public function set_gift_list(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $gift_list=Db::name('gift')->field('id,name,path,price')->where(array('status'=>1))->order('sort asc')->select();
        foreach ($gift_list as $k=>$v){
            if($gift_list[$k]['path']){
                $gift_list[$k]['path']=VIDEO_PATH.$gift_list[$k]['path'];
            }else{
                $gift_list[$k]['path']='';
            }
        }
        $redis->set('gift_list',serialize($gift_list));
    }
    //redis  轮播图
    public function set_banner_list(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $banner_list = Db::query("SELECT id,name,path,url,intro FROM `qm_ad` WHERE status=1 and cate_id=1");
        foreach ($banner_list as $k=>$v){
            if($banner_list[$k]['path']){
                $banner_list[$k]['path']=VIDEO_PATH.str_replace('\\','/', $banner_list[$k]['path']);
            }else{
                $banner_list[$k]['path']='';
            }
            if((int)$banner_list[$k]['url']>0){
                $banner_list[$k]['url_type']=1;//跳转内页
            }else{
                $banner_list[$k]['url_type']=2;//跳转外页
            }
            $banner_list[$k]['type']=2;//跳转外页
        }
        $redis->set('banner_list',serialize($banner_list));
    }
    //redis  启动广告
    public function set_ad_app_list(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $ad_app_list = Db::name('ad_app')->field('id,name,path,url')->where(array('status' => 1))->order('sort asc')->select();
            foreach ($ad_app_list as $k=>$v){
                if($ad_app_list[$k]['path']){
                    $ad_app_list[$k]['path']=VIDEO_PATH.$ad_app_list[$k]['path'];
                }else{
                    $ad_app_list[$k]['path']='';
                }
                if((int)$ad_app_list[$k]['url']>0){
                    $ad_app_list[$k]['url_type']=1;//跳转内页
                }else{
                    $ad_app_list[$k]['url_type']=2;//跳转外页
                }
            }

        $redis->set('ad_app_list',serialize($ad_app_list));
    }
    //redis   栏目
    public function set_column_list(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $column_list = Db::name('video_small_column')->field('id,name')->where(array('status' => 1))->order('sort asc')->select();
        $redis->set('column_list',serialize($column_list));
    }
    //redis  上映时间
    public function set_video_time_list(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $column_list = Db::name('video_small_column')->field('id')->where(array('status' => 1))->select();
        foreach ($column_list as $k=>$v){
            $time_list=Db::name('video_time')->field('id,start_time')->where(array('status'=>1,'column_id'=>$v['id']))->order('sort asc')->select();
            if($time_list){
                $new_time_list=array();
                $new_time_list[0]['id']='';
                $new_time_list[0]['start_time']='全部';
                $new_time_list[0]['name']='全部';
                foreach ($time_list as $key=>$val){
                    $time_list[$key]['name'] = (string)$time_list[$key]['start_time'];
                    $time_list[$key]['start_time']=(string)$time_list[$key]['start_time'];
                    $new_time_list[$key+1]=$time_list[$key];
                }
            }else{
                $new_time_list=array();
            }
            $redis->set('video_time_'.$v['id'],serialize($new_time_list));
        }

    }
    //redis  分类
    public function set_video_cate_list(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $column_list = Db::name('video_small_column')->field('id')->where(array('status' => 1))->select();
        foreach ($column_list as $k=>$v){
            $cate_list=Db::name('video_small_cate')->field('id,name')->where(array('status'=>1,'column_id'=>$v['id']))->order('sort asc')->select();
            if($cate_list){
                $new_cate_list=array();
                $new_cate_list[0]['id']='';
                $new_cate_list[0]['name']='全部';
                foreach ($cate_list as $key=>$val){
                    $new_cate_list[$key+1]=$cate_list[$key];
                }
            }else{
                $new_cate_list=array();
            }
            $redis->set('cate_list_'.$v['id'],serialize($new_cate_list));
        }

    }
    //redis  地区列表
    public function set_video_address_list(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $column_list = Db::name('video_small_column')->field('id')->where(array('status' => 1))->select();
        foreach ($column_list as $k=>$v){
            $address_list=Db::name('video_address')->field('id,name')->where(array('status'=>1,'column_id'=>$v['id']))->order('sort asc')->select();
            if($address_list){
                $new_address_list=array();
                $new_address_list[0]['id']='';
                $new_address_list[0]['name']='全部';
                foreach ($address_list as $key=>$val){
                    $new_address_list[$key+1]=$address_list[$key];
                }
            }else{
                $new_address_list=array();
            }
            $redis->set('address_list_'.$v['id'],serialize($new_address_list));
        }

    }
    //redis 栏目解说视频列表
    public function set_video_list(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $column_list = Db::name('video_small_column')->field('id')->where(array('status' => 1))->select();
        $start_time=strtotime(date('Y-m-d',time()).' 00:00:00')-3*86400;
        $end_time=strtotime(date('Y-m-d',time()).' 23:59:59')-86400;
        $where[] = array('createtime', 'between', [$start_time,$end_time]);
        $where[] = array('status', 'eq', 1);
        foreach ($column_list as $key=>$val){
            $video_list = Db::name('video_small')->field('id,title,fm_img as path,url,zan_num,trample_num,hits,createtime,video_time,uid as author_id,memo,column_id,tag,language,cate_id,video_time_id,video_id,comment_num')->where($where)->where(array('column_id'=>$val['id']))->limit(200)->order('sort asc,createtime desc')->select();
            foreach ($video_list as $k => $v) {
                $video_list[$k]['path'] = VIDEO_PATH .str_replace('\\','/', $video_list[$k]['path']);
                $user_re=Db::name('user')->field('name,path')->where(array('id'=>$v['author_id']))->find();
                $video_list[$k]['author_name']=$user_re['name'];
                if($user_re['path']){
                    $video_list[$k]['author_path']=VIDEO_PATH.str_replace('\\','/', $user_re['path']);
                }else{
                    $video_list[$k]['author_path']='';
                }
                $video_list[$k]['author_attention_status']=2;
                $video_list[$k]['zan_status'] = 2;
                $video_list[$k]['trample_status'] = 2;
                $video_list[$k]['video_attention_status']=2;
                if($video_list[$k]['url']){
                    $video_list[$k]['url']=VIDEO_PATH.str_replace('\\','/', $video_list[$k]['url']);
                }else{
                    $video_list[$k]['url']='';
                }
                $video_list[$k]['hits']=$this->get_hits($video_list[$k]['id'],4);
                if ($video_list[$k]['hits'] >= 10000 && $video_list[$k]['hits'] < 100000000) {
                    $video_list[$k]['hits'] = $video_list[$k]['hits'] / 10000;
                    $video_list[$k]['hits'] = round($video_list[$k]['hits'], 2) . '万';
                } elseif ($video_list[$k]['hits'] >= 100000000) {
                    $video_list[$k]['hits'] =$video_list[$k]['hits'] / 100000000;
                    $video_list[$k]['hits'] = round($video_list[$k]['hits'], 2) . '亿';
                }
                /*if($video_list[$k]['hits']>10000){
                    $video_list[$k]['hits']=floor($video_list[$k]['hits']/10000).'万';
                }*/
                $video_list[$k]['type']=1;
                $video_list[$k]['url_type']=1;
            }
            $redis->set('video_list_'.$val['id'],serialize($video_list),3600*24);
        }
        //全部解说视频
        $more_video_list = Db::name('video_small')->field('id,title,fm_img as path,url,zan_num,trample_num,hits,createtime,video_time,uid as author_id,memo,column_id,tag,language,cate_id,video_time_id,video_id,comment_num')->where($where)->limit(200)->order('createtime desc')->select();
        foreach ($more_video_list as $k => $v) {
            $more_video_list[$k]['path'] = VIDEO_PATH .str_replace('\\','/', $more_video_list[$k]['path']);
            $user_re=Db::name('user')->field('name,path')->where(array('id'=>$v['author_id']))->find();
            $more_video_list[$k]['author_name']=$user_re['name'];
            if($user_re['path']){
                $more_video_list[$k]['author_path']=VIDEO_PATH.str_replace('\\','/', $user_re['path']);
            }else{
                $more_video_list[$k]['author_path']='';
            }
            $more_video_list[$k]['author_attention_status']=2;
            $more_video_list[$k]['zan_status'] = 2;
            $more_video_list[$k]['trample_status'] = 2;
            $more_video_list[$k]['video_attention_status']=2;
            if($more_video_list[$k]['url']){
                $more_video_list[$k]['url']=VIDEO_PATH.str_replace('\\','/', $more_video_list[$k]['url']);
            }else{
                $more_video_list[$k]['url']='';
            }
            $more_video_list[$k]['hits']=$this->get_hits($more_video_list[$k]['id'],4);
            if ($more_video_list[$k]['hits'] >= 10000 && $more_video_list[$k]['hits'] < 100000000) {
                $more_video_list[$k]['hits'] = $more_video_list[$k]['hits'] / 10000;
                $more_video_list[$k]['hits'] = round($more_video_list[$k]['hits'], 2) . '万';
            } elseif ($more_video_list[$k]['hits'] >= 100000000) {
                $more_video_list[$k]['hits'] =$more_video_list[$k]['hits'] / 100000000;
                $more_video_list[$k]['hits'] = round($more_video_list[$k]['hits'], 2) . '亿';
            }
            /*if($more_video_list[$k]['hits']>10000){
                $more_video_list[$k]['hits']=floor($more_video_list[$k]['hits']/10000).'万';
            }*/
            $more_video_list[$k]['type']=1;
            $more_video_list[$k]['url_type']=1;
        }
        $redis->set('more_video_list',serialize($more_video_list),3600*24);

    }
    //更新视频详情
    public function set_video_info($video_id){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        if($redis->get('video_info_'.$video_id)){
            $video_re = Db::name('video_small')->field('id,title,fm_img as path,url,zan_num,trample_num,hits,createtime,video_time,uid as author_id,memo,column_id,tag,language,cate_id,video_time_id,video_id,comment_num')->where(array('id' => $video_id))->find();
            if ($video_re) {
                $redis->SETEX('video_info_' . $video_id, 3600, serialize($video_re));//1小时更新一次
            }
        }
    }
    //redis  分成比例
    public function set_commission($commission){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $redis->set('commission',$commission);
    }
    //记录用户历史浏览记录
    public function add_history($uid,$video_id,$column_id){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $user_history_result= $redis->HGET('user_history',$uid);
        $user_history_column_result= $redis->HGET('user_history_column',$uid);
        $user_history_time_result= $redis->HGET('user_history_time',$uid);
        if($user_history_result){
            $log_history_arr=explode(',',$user_history_result);
            $log_history_column_arr=explode(',',$user_history_column_result);
            $log_history_time_arr=explode(',',$user_history_time_result);
            $keys=array_keys($log_history_arr,$video_id);
            if($keys){
                unset($log_history_arr[$keys[0]]);
                unset($log_history_column_arr[$keys[0]]);
                unset($log_history_time_arr[$keys[0]]);
            }
            $now_history_str=implode(',',$log_history_arr);
            $now_history_column_str=implode(',',$log_history_column_arr);
            $now_history_time_str=implode(',',$log_history_time_arr);
            $redis->multi();
            if($now_history_str){
                $redis->HSET ('user_history',$uid,$now_history_str.','.$video_id);
                $redis->HSET ('user_history_column',$uid,$now_history_column_str.','.$column_id);
                $redis->HSET ('user_history_time',$uid,$now_history_time_str.','.time());
            }else{
                $redis->HSET ('user_history',$uid,$video_id);
                $redis->HSET ('user_history_column',$uid,$column_id);
                $redis->HSET ('user_history_time',$uid,time());
            }
            $redis->EXEC();
        }else{
            $redis->multi();
            $redis->HSET ('user_history',$uid,$video_id);
            $redis->HSET ('user_history_column',$uid,$column_id);
            $redis->HSET ('user_history_time',$uid,time());
            $redis->EXEC();
        }
        //加入队列
        $arr=array(
            'uid'=>$uid,
            'video_id'=>$video_id,
            'column_id'=>$column_id,
            'createtime'=>time()
        );
        $redis->LPUSH('history_list',serialize($arr));
    }
    //url转码
    function link_urldecode($url)
    {
        $uri = '';
        $cs = unpack('C*', $url);
        $len = count($cs);
        for ($i = 1; $i <= $len; $i++) {
            $uri .= $cs[$i] > 127 ? '%' . strtoupper(dechex($cs[$i])) : $url{$i - 1};
        }
        $uri=str_replace(' ','%20',$uri);
        return $uri;
    }
    //获取会员name,path
    public function get_user_info($uid,$type=2){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        if($type==1){
            $user_re = Db::name('user')->field('id,name,path,phone,coin,commission,reward_num,intro,pwd,qq_token,wx_token,vip_end,status')->where(array('id' => $uid))->find();
            if($user_re){
                if ($user_re['path']) {
                    if(count(explode('http',$user_re['path']))<2){
                        $user_re['path'] = VIDEO_PATH . str_replace('\\', '/', $user_re['path']);
                    }
                } else {
                    $user_re['path'] = '';
                }
            }else{
                $user_re['name'] = '此账号已删除';
                $user_re['path'] = VIDEO_PATH.'/uploads/upload_face/user_path.jpg';
            }

            $redis->HSET('user_info',$uid,serialize($user_re));
        }else{
            if(strlen($redis->HEXISTS('user_info',$uid))>0){
                $user_re=unserialize($redis->HGET('user_info',$uid));
            }else{
                $user_re = Db::name('user')->field('id,name,path,phone,coin,commission,reward_num,intro,pwd,qq_token,wx_token,vip_end,status')->where(array('id' => $uid))->find();
                if($user_re){
                    if ($user_re['path']) {
                        if(count(explode('http',$user_re['path']))<2){
                            $user_re['path'] = VIDEO_PATH . str_replace('\\', '/', $user_re['path']);
                        }
                    } else {
                        $user_re['path'] = '';
                    }
                }else{
                    $user_re['name'] = '此账号已删除';
                    $user_re['path'] = VIDEO_PATH.'/uploads/upload_face/user_path.jpg';
                }

                $redis->HSET('user_info',$uid,serialize($user_re));
            }
        }
        return $user_re;
    }
    //判断用户是否关注
    public function get_attent_status($uid,$type,$type_id){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $attention_result= $redis->HGET('follow_'.$type,$uid);
        if (in_array($type_id,explode(',',$attention_result))) {
            return 1;
        }else{
            return 2;
        }
       /* $attention_re = Db::name('attention')->field('id')->where(array('uid' => $uid, 'type' => $type, 'type_id' => $uid))->find();
        if ($attention_re) {
            return 1;
        } else {
            return 2;
        }*/
    }
    /*
     * 判断用户是否点赞
     * type 1点赞   2踩
     * 
     */
    public function get_zan_status($uid,$type,$type_id){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $video_zan_result= $redis->HGET('video_zan_'.$type,$uid);
        if (in_array($type_id,explode(',',$video_zan_result))) {
            return 1;
        } else {
            return 2;
        }
       /* $zan_re = Db::name('video_zan')->field('id')->where(array('uid' => $uid,'type'=>$type, 'type_id' => $type_id))->find();
        if ($zan_re) {
            return 1;
        } else{
            return 2;
        }*/
    }
    /*
     * 获取视频点击量
     * type  1日  2周  3月  4总
     */
    public function get_hits($video_id,$type){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        if($type==1){
            $key='video_hits_day';
        }elseif($type==2){
            $key='video_hits_week';
        }elseif($type==3){
            $key='video_hits_month';
        }elseif($type==4){
            $key='video_hits';
        }
        $result=$redis->ZSCORE($key,$video_id);
        if($result){
            return $result;
        }else{
            return 0;
        }
       
    }
    /*
    * 获取视频点赞/踩数
    * click_type  1点赞  2踩
    * type  1日  2周  3月  4总
    */
    public function get_zan_num($video_id,$click_type,$type=''){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        if($click_type==1){
            if($type==1){
                $key='video_small_zan_day';
            }elseif($type==2){
                $key='video_small_zan_week';
            }elseif($type==3){
                $key='video_small_zan_month';
            }elseif($type==4){
                $key='video_small_zan_num';
            }
        }else{
            $key='video_small_trample_num';
        }

        $result=$redis->ZSCORE($key,$video_id);
        if($result){
            return $result;
        }else{
            return 0;
        }

    }
    /*
     * 获取视频分类名称
     * $type 1 限时完整分类名称  2显示第一个
     *
     */
    public function get_video_cate($cate_id,$type=2){
        $cate_id_arr=explode(',', $cate_id);
        $cate_id_arr=array_filter($cate_id_arr);
        $cate_name='';
        if($type==2){
            $cate_re = Db::name('video_small_cate')->field('name')->where(array('id' => $cate_id_arr[0]))->find();
            if($cate_re){
                $cate_name= $cate_re['name'];
            }
        }else{
            foreach ($cate_id_arr as $k=>$v){
                $cate_re = Db::name('video_small_cate')->field('name')->where(array('id' => $cate_id_arr[$k]))->find();
                if($cate_re){
                    $cate_name.=$cate_re['name'].' ';
                }
            }
        }
        return $cate_name;
    }
    //更换视频地址更新redis
    public function update_redis(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        //删除会员信息
        $redis->hDel('user_info');
        //栏目解说视频列表
        $this->set_video_list();
        //启动广告
        $this->set_ad_app_list();
        //轮播图
        $this->set_banner_list();
        //礼物列表
        $this->set_gift_list();
    }
    function lock_test(){
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        $lock_token = rand(1, 100000);
        //如果没锁去加锁
        if ($this->lock($lock_token)) {
            // do something
            //$redis->INCR ('a',1);
            echo '有锁';
            $this->unlock($lock_token);
        }
    }
    /*
    *
    *ex seconds--设置指定的过期时间，以秒为单位。<br>
    *px millises--设置指定的过期时间（毫秒）。<br>
    *px millises--设置指定的过期时间（毫秒）。<br>
    *nx——仅当密钥不存在时才设置该密钥。<br>
    *xx——只设置已经存在的键。<br>
    */
    function lock($lock_token) {
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);

        //return $redis->set("my:lock", $token, "nx", "ex", 10);
        return $redis->set("my:lock", $lock_token,  ['nx', 'ex' => 60]);
    }

    function unlock($lock_token) {
        // lua 脚本解锁
        // 先判断 key的值是否为 value, TRUE 才会删除, 所以 $value 的设计要有随机唯一性
        $script ="if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        $redis = new \Redis();
        $redis->connect('127.0.0.1', REDIS_PORT);
        $redis->auth(REDIS_PASSWORD);
        echo $lock_token;
        return $redis->eval($script, array('my:lock',$lock_token),1);
    }
    //验证签名
    public function check_sign($arr,$sign,$timestamp=''){
        //if(time()-$timestamp<120){
            $token=TOKEN;
            unset($arr['timestamp']);
            unset($arr['sign']);
            ksort($arr);
            $str='';
            foreach ($arr as $k=>$v){
                $str.=$k.'='.$v.'&';
                //$str.=$k.$v;
            }
            $str.='token='.$token;
            //$str.=$token;
            //echo $str;
            $md5_sign= strtoupper((string)md5($str));
            if($sign==$md5_sign){
                return 1;
            }else{
                return 2;
            }
        /*}else{
            return 3;
        }*/

    }
    /*
     * 记录管理员操作 日志
     * type  1 添加   2修改  3 删除
     */
    public function add_admin_log($type,$info){
        $arr=array(
            'admin_id'=>session('qm_uid'),
            'type'=>$type,
            'info'=>$info,
            'createtime'=>time(),
        );
        Db::name('admin_log')->insert($arr);
    }
    
}